package cn.silver.module.monitor.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.silver.framework.core.constant.CacheConstants;
import cn.silver.framework.core.utils.StreamUtils;
import cn.silver.framework.core.utils.StringUtils;
import cn.silver.framework.log.annotation.Log;
import cn.silver.framework.log.enums.OperateEnums;
import cn.silver.framework.openapi.model.Result;
import cn.silver.framework.openapi.model.ResultPage;
import cn.silver.framework.redis.utils.RedisUtils;
import cn.silver.framework.satoken.model.OnlineModel;
import cn.silver.framework.web.controller.ApiController;
import cn.silver.module.monitor.domain.OnlineUser;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 在线用户监控
 *
 * @author Silver Zhou
 */
@RestController
@RequiredArgsConstructor
@Tag(name = "系统监控-在线用户管理")
@RequestMapping("/monitor/online")
public class OnlineController extends ApiController {

    /**
     * 获取在线用户监控列表
     *
     * @param ipaddr   IP地址
     * @param userName 用户名
     */
    @GetMapping("/list")
    @SaCheckPermission("monitor:online:list")
    public ResultPage<OnlineModel> list(String ipaddr, String userName) {
        // 获取所有未过期的 token
        List<String> keys = StpUtil.searchTokenValue("", 0, -1, false);
        List<OnlineModel> onlineModelList = new ArrayList<>();
        for (String key : keys) {
            String token = StringUtils.substringAfterLast(key, ":");
            // 如果已经过期则跳过
            if (StpUtil.stpLogic.getTokenActiveTimeoutByToken(token) < -1) {
                continue;
            }
            OnlineModel object = RedisUtils.getCacheObject(CacheConstants.ONLINE_TOKEN_KEY, token);
            onlineModelList.add(object);
        }
        if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) {
            onlineModelList = StreamUtils.filter(onlineModelList, userOnline ->
                    StringUtils.equals(ipaddr, userOnline.getIpaddr()) &&
                            StringUtils.equals(userName, userOnline.getUserName())
            );
        } else if (StringUtils.isNotEmpty(ipaddr)) {
            onlineModelList = StreamUtils.filter(onlineModelList, userOnline ->
                    StringUtils.equals(ipaddr, userOnline.getIpaddr())
            );
        } else if (StringUtils.isNotEmpty(userName)) {
            onlineModelList = StreamUtils.filter(onlineModelList, userOnline ->
                    StringUtils.equals(userName, userOnline.getUserName())
            );
        }
        Collections.reverse(onlineModelList);
        onlineModelList.removeAll(Collections.singleton(null));
        List<OnlineUser> userOnlineList = BeanUtil.copyToList(onlineModelList, OnlineUser.class);
        return ResultPage.build(onlineModelList);
    }

    /**
     * 强退用户
     *
     * @param tokens token值
     */
    @DeleteMapping("/{tokens}")
    @SaCheckPermission("monitor:online:forceLogout")
    @Log(title = "在线用户", operate = OperateEnums.SYS_FORCE)
    public Result<Void> forceLogout(@PathVariable String[] tokens) {
        try {
            for (String token : tokens) {
                StpUtil.kickoutByTokenValue(token);
            }
        } catch (NotLoginException ignored) {
        }
        return Result.ok();
    }
}
